/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.econsole.modules.api.service.impl.QueryServiceImpl.java 
 * <p>
 * 类产生时间: 2014-7-23 0023 上午 10:55
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.econsole.modules.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.oceansoft.mobile.econsole.cache.redis.CacheBaseService;
import com.oceansoft.mobile.econsole.common.constant.Constant;
import com.oceansoft.mobile.econsole.common.util.FileUtils;
import com.oceansoft.mobile.econsole.common.util.HttpClientUtil;
import com.oceansoft.mobile.econsole.common.util.MD5Util;
import com.oceansoft.mobile.econsole.common.util.StringUtils;
import com.oceansoft.mobile.econsole.common.util.image.ImageUtil;
import com.oceansoft.mobile.econsole.modules.api.entity.*;
import com.oceansoft.mobile.econsole.modules.api.persistence.IMattersMapper;
import com.oceansoft.mobile.econsole.modules.api.persistence.IRoadMapper;
import com.oceansoft.mobile.econsole.modules.api.service.IQueryService;
import com.oceansoft.mobile.econsole.modules.base.entity.Query;
import com.oceansoft.mobile.econsole.modules.base.entity.Result;
import com.oceansoft.mobile.econsole.modules.jlapi.entity.*;
import com.oceansoft.mobile.econsole.modules.jlapi.persistence.IJlApiInfoMapper;
import com.oceansoft.mobile.econsole.modules.jlapi.service.IJlApiService;
import com.oceansoft.mobile.econsole.modules.member.service.IMemberService;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 * 查询服务实体类
 *
 * @author: chenw
 * @time: 2014-7-23 0023 上午 10:55
 */
@Service
public class QueryServiceImpl extends CacheBaseService implements IQueryService {

    private static Logger logger = org.slf4j.LoggerFactory.getLogger(QueryServiceImpl.class);

    @Resource
    private IRoadMapper roadMapper;

    @Resource
    private IMemberService iMemberService;

    @Resource
    private IJlApiService jlApiService;

    @Resource
    private IMattersMapper mattersMapper;

    @Resource
    private IJlApiInfoMapper jlApiInfoMapper;

    private static JSONObject parseXML(String response) throws IOException, SAXException, ParserConfigurationException {
        final JSONObject result = new JSONObject(2);
        final String TAG_NODE_HEAD = "HEAD";
        final String TAG_NODE_BODY = "BODY";
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        parser.parse(new ByteArrayInputStream(response.getBytes("UTF-8")), new DefaultHandler() {
            String parentNode;
            JSONObject temp;
            String currText;

            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                if (TAG_NODE_HEAD.equalsIgnoreCase(qName) || TAG_NODE_BODY.equalsIgnoreCase(qName)) {
                    temp = new JSONObject();
                    parentNode = qName;
                }
            }

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                currText = new String(ch, start, length);
            }

            @Override
            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (TAG_NODE_HEAD.equalsIgnoreCase(qName)) {
                    result.put("head", temp);
                    temp = null;
                } else if (TAG_NODE_BODY.equalsIgnoreCase(qName)) {
                    result.put("body", temp);
                    temp = null;
                } else {
                    if (null != temp) {
                        temp.put(qName, currText);
                        currText = null;
                    }
                }
            }

            @Override
            public void error(SAXParseException e) throws SAXException {
                System.out.println("响应结果SAX解析错误！");
            }

            @Override
            public void endDocument() throws SAXException {
                temp = null;
                parentNode = null;
                currText = null;
            }
        });
        return result;
    }

    @Override
    public Result queryTrafficeViolation(VehicleInfo vehicleInfo) {
        String key = "Wei20131101", url = "http://violate.2500city.com/api/query";
        long timestamp = System.currentTimeMillis();
        JSONObject data = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("tradeId", "queryVehicleViolation");
        header.put("timestamp", timestamp);
        header.put("validCode", MD5Util.getMD5String(timestamp + key));
        header.put("appKey", "C100022");
        JSONObject body = new JSONObject();
        body.put("HPHM", vehicleInfo.getLicense().toUpperCase().replace("0", "0").replace("I", "1"));
        body.put("CLSBDH", vehicleInfo.getVin().toUpperCase().replace("0", "0").replace("I", "1"));
        body.put("HPZL", "02");
        data.put("head", header);
        data.put("body", body);
        System.out.println("==============================>" + data);
        String response = HttpClientUtil.doPostString(url, data);
        System.out.println("==============================>" + response);
        JSONObject respObj = JSON.parseObject(response);
        if (null != respObj && StringUtils.isBlank(respObj.getString("errormsg"))) {
            JSONArray array = respObj.getJSONArray("result");
            int size = array.size();
            if (size > 0) {
                ArrayList list = new ArrayList(array.size());
                for (int i = 0; i < size; i++) {
                    JSONObject obj = array.getJSONObject(i);
                    JSONArray photos = obj.getJSONArray("image");
                    List<String> photoStr = null;
                    if (photos != null) {
                        photoStr = new ArrayList<String>(photos.size());
                        for (Object photo : photos) {
                            photoStr.add(photo.toString());
                        }
                    }
                    int clbj = 0;
                    int jkbj = 0;
                    if (obj.get("CLBJ") != null) {
                        clbj = obj.getInteger("CLBJ");
                    }
                    if (obj.get("JKBJ") != null) {
                        jkbj = obj.getInteger("JKBJ");
                    }
                    list.add(new ViolationInfo(obj.getString("JDSBH"),
                            obj.getString("FXJGMC"),
                            obj.getString("WFSJ"),
                            obj.getString("WFXW"),
                            obj.getString("WFDZ"),
                            obj.getFloat("FKJE"),
                            1 == clbj ? "已处理" : "未处理",
                            1 == jkbj ? "已缴款" : "未缴款",
                            photoStr));
                }
                return new Result(list);
            } else {
                return new Result("暂无违章记录");
            }
        } else {
            return new Result(Result.FAILURE, respObj.getString("errormsg"));
        }
    }

    @Override
    public Result queryDriverInfo(DriverInfo driverInfo) {
        String key = "Wei20131101", url = "http://violate.2500city.com/api/query";
        long timestamp = System.currentTimeMillis();
        JSONObject data = new JSONObject();
        JSONObject header = new JSONObject();
        header.put("tradeId", "queryDriverInfo");
        header.put("timestamp", timestamp);
        header.put("validCode", MD5Util.getMD5String(timestamp + key));
        header.put("appKey", "C100022");
        JSONObject body = new JSONObject();
        body.put("JSZH", driverInfo.getDrivingLicense());
        body.put("DABH", driverInfo.getFn());
        data.put("head", header);
        data.put("body", body);
        String response = HttpClientUtil.doPostString(url, data);
        JSONObject respObj = JSON.parseObject(response);
        if (null != respObj && StringUtils.isBlank(respObj.getString("errormsg"))) {
            JSONArray array = respObj.getJSONArray("result");
            int size = array.size();
            if (size > 0) {
                return new Result(array.get(0));
            } else {
                return new Result("未找到相关驾驶员信息");
            }
        } else {
            return new Result(respObj.getString("errormsg"));
        }
    }

    @Override
    public Result loadCaseProgress(final String caseId) {
        /*String response = emulatorLogin(caseId);
        return processResponse(response);*/
        List<ProgressResult> list = mattersMapper.loadCaseProgress(caseId);
        if(null != list && 0 < list.size()){
            return new Result(Result.SUCC,list.get(0));
        }
        return new Result(Result.FAILURE);
    }

    @Override
    public Result loadWeatherForecastInfo() {
        String key = "LOAD:WEATHER:FORECAST:INFO";
        if (super.exists(key)) {
            return new Result(Result.SUCC, super.getObject(key));
        } else {
            try {
                JSONObject result = load7DaysWeather();
                super.cache(key, result, 30 * 60);
                return new Result(Result.SUCC, result);
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(Result.FAILURE, "天气信息加载失败");
            }
        }
    }

    /**
     * 加载未来七天天气预报信息
     *
     * @return 天气信息集合
     */
    private JSONObject load7DaysWeather() throws IOException {
        JSONObject result = new JSONObject(3);
        Document document = Jsoup.connect(super.configInfo.getBizUrlWeatherReport()).get();
        //解析今后7天
        JSONArray weekWeather = new JSONArray(7);
        Elements weekdays = document.getElementById("7d").getElementsByTag("li");
        for (Element e_day : weekdays) {
            JSONObject _d = new JSONObject();
            _d.put("week", e_day.child(0).text());
            _d.put("day", e_day.child(1).text());
            _d.put("picD", e_day.child(2).removeClass("jpg50").className().replace("d", ""));
            _d.put("picN", e_day.child(3).removeClass("jpg50").className().replace("n", ""));
            _d.put("weather", e_day.child(4).text());
            Elements temp = e_day.getElementsByClass("tem");
            _d.put("temp", String.format("%s/%s", temp.get(0).text(), temp.get(1).text()));
            Element win = e_day.getElementsByClass("win").get(0);
            Elements windDir = win.getElementsByTag("span");
            String dirA, dirB;
            dirA = windDir.get(0).attr("title");
            if (windDir.size() > 1) {
                dirB = windDir.get(1).attr("title");
            } else {
                dirB = dirA;
            }
            String windText = win.getElementsByTag("i").get(0).text();
            if (dirA.equals(dirB)) {
                _d.put("windPower", String.format("%s%s", dirA, windText));
            } else {
                if (windText.contains("转")) {
                    String[] _text = windText.split("转");
                    _d.put("windPower", String.format("%s%s转%s%s", dirA, _text[0], dirB, _text[1]));
                } else {
                    _d.put("windPower", String.format("%s转%s%s", dirA, dirB, windText));
                }
            }
            weekWeather.add(_d);
        }
        result.put("week", weekWeather);
        //解析今天天气：
        Elements today = document.getElementById("today").getElementsByTag("li");
        Element day = today.get(1);//今天白天
        JSONObject weatherDay = new JSONObject();
        weatherDay.put("pubTime", day.child(0).text());
        weatherDay.put("image", day.child(1).removeClass("jpg80").className().replaceAll("d|n", ""));
        weatherDay.put("weather", day.child(2).text());
        weatherDay.put("temp", day.child(3).text());
        weatherDay.put("windDir", day.child(4).child(0).attr("title"));
        weatherDay.put("windPower", day.child(4).text());
        weatherDay.put("sunrise", day.child(5).text());
        result.put("day", weatherDay);
        Element night = today.get(2);//今天晚上
        JSONObject weatherNight = new JSONObject();
        weatherNight.put("pubTime", night.child(0).text());
        weatherNight.put("image", night.child(1).removeClass("jpg80").className().replaceAll("d|n", ""));
        weatherNight.put("weather", night.child(2).text());
        weatherNight.put("temp", night.child(3).text());
        weatherNight.put("windDir", night.child(4).child(0).attr("title"));
        weatherNight.put("windPower", night.child(4).text());
        weatherNight.put("sunset", night.child(5).text());
        result.put("night", weatherNight);
        return result;
    }

    /**
     * 处理响应结果字符串
     *
     * @param response 响应结果内容
     * @return Result
     */
    private Result processResponse(String response) {
        if (StringUtils.isNotBlank(response)) {
            String result = null;
            if (StringUtils.isNotBlank(response)) {
                int start = response.indexOf("|alert");
                if (start > 0) { //错误提醒
                    start += 6;
                    int end = start + response.substring(start).indexOf("|");
                    result = response.substring(start, end).replaceAll("[(')\\s;]", "");
                    return new Result(Result.FAILURE, result);
                } else {//查询正确返回
                    //TODO:根据正确的业务数据查询结果解析
                    result = "正在审核";
                }
            }
            return new Result(result);
        } else {
            return new Result("查无查询结果");
        }
    }

    @Override
    @Transactional
    public Result loadRepetitiveName(HttpServletRequest request) {
        /*String cacheKey = "REPEAT:NAME:" + name;
        if (super.exists(cacheKey))
            return new Result(Result.SUCC, super.get(cacheKey), "查询成功");
        String reqestTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String param = "<Request><Head><DeptID>GONGANJU</DeptID><SysInfo>公安局</SysInfo><APPID>NAMENUM</APPID><RequestTime>" + reqestTime + "</RequestTime><HashSign/><Version>1</Version><Priority>1</Priority></Head><Body><NAME>" + name + "</NAME></Body></Request>";
        String response = new SZRkkAuthPersonNameServiceService().getSZRkkAuthPersonNameServicePort().execute(param);
        try {
            Integer num = Integer.valueOf(parseXML(response).getJSONObject("body").getIntValue("NUM"));
            super.cache(cacheKey, num, 24 * 60 * 60);
            return new Result(Result.SUCC, num, "查询成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            return new Result("查询数据失败");
        }*/
        String name = request.getParameter("name");
        if (StringUtils.isBlank(name)) {
            return new Result(Result.FAILURE,"请输入查询用户名!");
        }

        String pushType = request.getParameter("pushType");
        String pushId = request.getParameter("pushId");
        if(StringUtils.isBlank(pushType)){
            return new Result(Result.FAILURE,"请输入推送渠道!");
        }
        if(StringUtils.isBlank(pushId)){
            return new Result(Result.FAILURE,"请输入推送对象!");
        }

        // 生成消息推送类（微信模板，极光，短信）
        ApiMessage message = getApiMessage(pushType,pushId);

        NameSakeSearchCondition nameSakeSearchCondition = new NameSakeSearchCondition();
        nameSakeSearchCondition.setXm(name);

        String command = JSON.toJSONString(nameSakeSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_006, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        jlApiService.doExecute(inQueryServiceInfo,message);

        return new Result(Result.SUCC,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
    }

    @Override
    @Transactional
    public Result ytLoadRepetitiveName(HttpServletRequest request) throws IOException {

        String name = request.getParameter("name");
        if (StringUtils.isBlank(name)) {
            return new Result(Result.FAILURE,"请输入查询用户名!");
        }

        String url = configInfo.getServiceInterfaceAddress() + "/querys/wxname/"+name;

        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));
        System.out.println("result结果="+HttpClientUtil.doGet(url));
        if(null!= object.getJSONObject("data")){
            return new Result(Result.SUCC,object.getJSONObject("data"));
        }

        return new Result(Result.FAILURE);

    }

    @Override
    public Result loadNameRepeatQuery(HttpServletRequest request) {
        String name = request.getParameter("name");
        if (StringUtils.isBlank(name)) {
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"请输入查询用户名!");
        }

        NameSakeSearchCondition nameSakeSearchCondition = new NameSakeSearchCondition();
        nameSakeSearchCondition.setXm(name);

        String command = JSON.toJSONString(nameSakeSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_006, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);


        OutQueryServiceInfo outQueryServiceInfo = jlApiService.queryOutServiceInfoByCondition(InQueryServiceInfo.API_006,command);
        if(null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())){
            // 获取重名查询结果成功、状态码为 100101
            NameSakeInfo nameSakeInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), NameSakeInfo.class);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100101,nameSakeInfo,"获取重名查询结果成功");
        }else {
            // 请求已提交，查询结果稍后将以站内消息发送给您，请注意查收、状态码为 100102
            jlApiService.insertInServiceInfo(inQueryServiceInfo);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100102,inQueryServiceInfo,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
        }
    }

    @Override
    @Transactional
    public Result queryIdNumCheck(String guid,String xm,String sfzh){
        PermanentPopulationSearchCondition realNameCondition = new PermanentPopulationSearchCondition();
        realNameCondition.setGmsfhm(sfzh);
        realNameCondition.setXm(xm);
        realNameCondition.setUserguid(guid);

        String command = JSON.toJSONString(realNameCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_001, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), "127.0.0.1", 0);

        jlApiService.doSmrz(inQueryServiceInfo);

        return new Result(Result.SUCC,"请求已提交");
    }

    @Override
    @Transactional
    public Result queryIdNumCheck(HttpServletRequest request) {
        String idNum = request.getParameter("idNum");
        if (StringUtils.isBlank(idNum)) {
            return new Result(Result.FAILURE,"请输入查询身份证号!");
        }

        String pushType = request.getParameter("pushType");
        String pushId = request.getParameter("pushId");
        if(StringUtils.isBlank(pushType)){
            return new Result(Result.FAILURE,"请输入推送渠道!");
        }
        if(StringUtils.isBlank(pushId)){
            return new Result(Result.FAILURE,"请输入推送对象!");
        }

        // 生成消息推送类（微信模板，极光，短信）
        ApiMessage message = getApiMessage(pushType,pushId);

        PermanentPopulationSearchCondition realNameCondition = new PermanentPopulationSearchCondition();
        realNameCondition.setGmsfhm(idNum);

        String command = JSON.toJSONString(realNameCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_001, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        jlApiService.doExecute(inQueryServiceInfo,message);

        return new Result(Result.SUCC,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
    }

    @Override
    @Transactional
    public Result queryVehicleCheck(HttpServletRequest request) {
        String vehicleNum = request.getParameter("vehicleNum");
        if (StringUtils.isBlank(vehicleNum)) {
            return new Result(Result.FAILURE,"请输入查询车牌号!");
        }

        String pushType = request.getParameter("pushType");
        String pushId = request.getParameter("pushId");
        if(StringUtils.isBlank(pushType)){
            return new Result(Result.FAILURE,"请输入推送渠道!");
        }
        if(StringUtils.isBlank(pushId)){
            return new Result(Result.FAILURE,"请输入推送对象!");
        }

        // 生成消息推送类（微信模板，极光，短信）
        ApiMessage message = getApiMessage(pushType,pushId);

        VehicleSearchCondition vehicleSearchCondition = new VehicleSearchCondition();
        vehicleSearchCondition.setJdchphm(vehicleNum);

        String command = JSON.toJSONString(vehicleSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_003, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        jlApiService.doExecute(inQueryServiceInfo,message);

        return new Result(Result.SUCC,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
    }

    @Override
    public Result loadWtCarTypeList(String typeId) {
        List<CarType> list = (List<CarType>)super.getObject("CAR:TYPE:"+typeId);
//        super.delCache("CAR:TYPE:"+typeId);
        if(null == list){
            list = mattersMapper.loadWtCarTypeList(typeId);
            if(null != list){
                super.cache("car:type:"+typeId,list,1F);
                return new Result(Result.SUCC,list);
            }
        }else {
            return new Result(Result.SUCC,list);
        }

        return new Result(Result.FAILURE,"获取失败");
    }

    @Override
    @Transactional
    public Result loadVehicleIllegalList(HttpServletRequest request) {

        String jdccllxbm = request.getParameter("jdccllxbm");
        if (StringUtils.isBlank(jdccllxbm)) {
            return new Result(Result.FAILURE,"请输入机动车车辆类型代码!");
        }
        String fdj = request.getParameter("fdj");
        if (StringUtils.isBlank(fdj)) {
            return new Result(Result.FAILURE,"请输入发动机后六位!");
        }
        String jdchphm = request.getParameter("jdchphm");
        if (StringUtils.isBlank(jdchphm)) {
            return new Result(Result.FAILURE,"请输入机动车车牌号码!");
        }else {
            jdchphm = "辽"+jdchphm;
        }

        String pushType = request.getParameter("pushType");
        String pushId = request.getParameter("pushId");
        if(StringUtils.isBlank(pushType)){
            return new Result(Result.FAILURE,"请输入推送渠道!");
        }
        if(StringUtils.isBlank(pushId)){
            return new Result(Result.FAILURE,"请输入推送对象!");
        }

        // 生成消息推送类（微信模板，极光，短信）
        ApiMessage message = getApiMessage(pushType,pushId);

        OffenseVehicleSearchCondition offenseVehicleSearchCondition = new OffenseVehicleSearchCondition();
        offenseVehicleSearchCondition.setFdj(fdj);
        offenseVehicleSearchCondition.setJdccllxbm(jdccllxbm);
        offenseVehicleSearchCondition.setJdchphm(jdchphm);

        String command = JSON.toJSONString(offenseVehicleSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_002, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        jlApiService.doExecute(inQueryServiceInfo,message);

        return new Result(Result.SUCC,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
    }

    @Override
    public Result loadVehicleIllegalLists(OffenseVehicleSearchCondition vehicleSearch) {

        String command = JSON.toJSONString(vehicleSearch);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_002, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), "127.0.0.1", 0);

        List<OffenseVehicleInfo> list = jlApiService.doExecutes(inQueryServiceInfo);

        //违法原因通过CODE返回详细情况
        try {
            if (null!=list&&!list.isEmpty()) {
                String wzyy;
                for (OffenseVehicleInfo vehicleInfo : list) {
                    wzyy = vehicleInfo.getWzyy();
                    vehicleInfo.setWzyy(iMemberService.findCode(wzyy));
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(Result.SUCC,list);
    }

    @Override
    public Result ytVehicleIllegalLists(OffenseVehicleSearchCondition vehicleSearch) throws IOException {
        String url = configInfo.getServiceInterfaceAddress() + "/querys/queryViolationNoCode?apiType="+"3" +"&hpzl=" + vehicleSearch.getJdccllxbm() + "&hphm="+vehicleSearch.getJdchphm().toUpperCase() +"&fdjh=" + vehicleSearch.getFdj();
        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));
        System.out.println("apiPager.getList()="+HttpClientUtil.doGet(url));

        if(null!= object.getJSONObject("data")){
            return new Result(Result.SUCC,object.getJSONObject("data"));
        }

        return new Result(Result.FAILURE);
    }

    @Override
    public Result ytLicensePointsInfo(HttpServletRequest request) throws IOException {
        String url = configInfo.getServiceInterfaceAddress() + "/querys/queryViolationNoCode?apiType="+"1" +"&sfzmhm=" + request.getParameter("jtglywdxsfzhm") ;
        JSONObject object = JSON.parseObject(HttpClientUtil.doGet(url));
        System.out.println("apiPager.getList()="+HttpClientUtil.doGet(url));
        if(null!= object.getJSONObject("data")){
            if(object.getJSONObject("data").getJSONArray("result").size()!=0){
                return new Result(Result.SUCC,(JSONObject)object.getJSONObject("data").getJSONArray("result").get(0));
            }else{
                return new Result(Result.FAILURE);
            }
        }
        return new Result(Result.FAILURE);
    }



    @Override
    public Result loadVehicleclcxLists(HttpServletRequest request) {

        String jdccllxbm = request.getParameter("jdccllxbm");
        if (StringUtils.isBlank(jdccllxbm)) {
            return new Result(Result.FAILURE,"请输入机动车车辆类型代码!");
        }
        String fdj = request.getParameter("fdj");
        if (StringUtils.isBlank(fdj)) {
            return new Result(Result.FAILURE,"请输入车辆识别代码!");
        }
        String jdchphm = request.getParameter("jdchphm");
        if (StringUtils.isBlank(jdchphm)) {
            return new Result(Result.FAILURE,"请输入机动车车牌号码!");
        }



        CarSearchInfo carSearchInfo = new CarSearchInfo();
        carSearchInfo.setHpzl(jdccllxbm);
        carSearchInfo.setClsbdh(fdj);
       carSearchInfo.setJdchphm(jdchphm);

        String command = JSON.toJSONString(carSearchInfo);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_003, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        Vehicle vehicle = null;
        try {
            vehicle = jlApiService.doExecutes3(inQueryServiceInfo);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return new Result(Result.SUCC,vehicle);
    }

    @Override
    public Result loadcarIllegalList(HttpServletRequest request) {

        String jdccllxbm = request.getParameter("jdccllxbm");
        if (StringUtils.isBlank(jdccllxbm)) {
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"请输入机动车车辆类型代码!");
        }
        String fdj = request.getParameter("fdj");
        if (StringUtils.isBlank(fdj)) {
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"请输入发动机后六位!");
        }
        String jdchphm = request.getParameter("jdchphm");
        if (StringUtils.isBlank(jdchphm)) {
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"请输入机动车车牌号码!");
        }else {
            jdchphm = "辽"+jdchphm;
        }

        OffenseVehicleSearchCondition offenseVehicleSearchCondition = new OffenseVehicleSearchCondition();
        offenseVehicleSearchCondition.setFdj(fdj);
        offenseVehicleSearchCondition.setJdccllxbm(jdccllxbm);
        offenseVehicleSearchCondition.setJdchphm(jdchphm);

        String command = JSON.toJSONString(offenseVehicleSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_002, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        OutQueryServiceInfo outQueryServiceInfo = jlApiService.queryOutServiceInfoByCondition(InQueryServiceInfo.API_002,command);
        if(null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())){
            // 获取机动车违法列表成功、状态码为 100101
            List<OffenseVehicleInfo> list = JSONArray.parseArray(outQueryServiceInfo.getRes(),OffenseVehicleInfo.class);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100101,list,"获取机动车违法列表成功");
        } else if(null != outQueryServiceInfo && outQueryServiceInfo.getCode()=="111111"){
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"您输入的发动机号与车牌号不匹配，请确认后再查询！");
        } else {
            // 请求已提交，查询结果稍后将以站内消息发送给您，请注意查收、状态码为 100102
            jlApiService.insertInServiceInfo(inQueryServiceInfo);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100102,inQueryServiceInfo,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
        }

    }

    @Override
public Result loadLicensePointsInfo(HttpServletRequest request) {

        String dabh = request.getParameter("dabh");
        if (StringUtils.isBlank(dabh)) {
            return new Result(Result.FAILURE,"请输入驾驶证档案编号!");
        }
        String jtglywdxsfzhm = request.getParameter("jtglywdxsfzhm");
        if (StringUtils.isBlank(jtglywdxsfzhm)) {
            return new Result(Result.FAILURE,"请输入驾驶证号码!");
        }
//        String pushType = request.getParameter("pushType");
//        String pushId = request.getParameter("pushId");
//        if(StringUtils.isBlank(pushType)){
//            return new Result(Result.FAILURE,"请输入推送渠道!");
//        }
//        if(StringUtils.isBlank(pushId)){
//            return new Result(Result.FAILURE,"请输入推送对象!");
//        }
//
//        // 生成消息推送类（微信模板，极光，短信）
//        ApiMessage message = getApiMessage(pushType,pushId);

        DriverLicenseSearchCondition driverLicenseSearchCondition = new DriverLicenseSearchCondition();
        driverLicenseSearchCondition.setDabh(dabh);
        driverLicenseSearchCondition.setJtglywdxsfzhm(jtglywdxsfzhm);

        String command = JSON.toJSONString(driverLicenseSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_007, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

//        jlApiService.doExecute(inQueryServiceInfo,message);
       DriverLicenseInfo list=new DriverLicenseInfo();
        try {
            list=    jlApiService.doExecutes2(inQueryServiceInfo);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return new Result(Result.SUCC,list);

    }

    @Override
    public Result loadDriverPointsInfo(HttpServletRequest request) {
        String dabh = request.getParameter("dabh");
        if (StringUtils.isBlank(dabh)) {
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"请输入驾驶证档案编号!");
        }
        String jtglywdxsfzhm = request.getParameter("jtglywdxsfzhm");
        if (StringUtils.isBlank(jtglywdxsfzhm)) {
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"请输入驾驶证号码!");
        }

        DriverLicenseSearchCondition driverLicenseSearchCondition = new DriverLicenseSearchCondition();
        driverLicenseSearchCondition.setDabh(dabh);
        driverLicenseSearchCondition.setJtglywdxsfzhm(jtglywdxsfzhm);

        String command = JSON.toJSONString(driverLicenseSearchCondition);
        InQueryServiceInfo inQueryServiceInfo
                = new InQueryServiceInfo(UUID.randomUUID().toString().replace("-", "")
                , InQueryServiceInfo.API_007, InQueryServiceInfo.API_ASYNC_Y, command
                , MD5Util.getMD5String(command), new Date(), request.getRemoteHost(), 0);

        OutQueryServiceInfo outQueryServiceInfo = jlApiService.queryOutServiceInfoByCondition(InQueryServiceInfo.API_007,command);
        if(null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())){
            // 获取驾驶证记分成功、状态码为 100101
            DriverLicenseInfo driverLicenseInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), DriverLicenseInfo.class);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100101,driverLicenseInfo,"获取驾驶证记分成功");
        }else {
            // 请求已提交，查询结果稍后将以站内消息发送给您，请注意查收、状态码为 100102
            jlApiService.insertInServiceInfo(inQueryServiceInfo);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100102,inQueryServiceInfo,"请求已提交，查询结果稍后将以站内消息发送给您，请注意查收");
        }

    }

    @Override
    @Transactional
    public Object loadResultGain(String sn, String action) {
        OutQueryServiceInfo outQueryServiceInfo = getObject("APP:QUERY:"+action+":"+sn,OutQueryServiceInfo.class);    //上传已经存在数据
        if(null == outQueryServiceInfo){

            List<OutQueryServiceInfo>  outQueryServiceInfos = jlApiInfoMapper.queryListOutServiceInfo(sn);
            if(null != outQueryServiceInfos && outQueryServiceInfos.size()>0){
                outQueryServiceInfo = outQueryServiceInfos.get(0);
                cache("app:query:"+action+":"+sn,outQueryServiceInfo,24*3600);
            }
        }

        if(null != outQueryServiceInfo){
            if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_001)){
                //实名认证
                RealNameAuthInfo realNameAuthInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), RealNameAuthInfo.class);
                return realNameAuthInfo;

            }else if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_002)){
                // 车辆违章查询
                List<OffenseVehicleInfo> list = JSONArray.parseArray(outQueryServiceInfo.getRes(),OffenseVehicleInfo.class);
                return list;

            }else if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_003)){
                // 车辆查询
                List<VehicleItem> list = JSONArray.parseArray(outQueryServiceInfo.getRes(),VehicleItem.class);
                return list;

            }else if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_004)){
                // 驾驶员查询
                JLDriverInfo jlDriverInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), JLDriverInfo.class);
                return jlDriverInfo;

            }else if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_005)){
                // 已决在押人员
                List<YjZyPersonInfo> list = JSONArray.parseArray(outQueryServiceInfo.getRes(), YjZyPersonInfo.class);
                return list;

            }else if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_006)){
                // 重名查询
                NameSakeInfo nameSakeInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), NameSakeInfo.class);
                return nameSakeInfo;

            }else if(outQueryServiceInfo.getAction().equals(InQueryServiceInfo.API_007)){
                // 驾照查询
                DriverLicenseInfo driverLicenseInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), DriverLicenseInfo.class);
                return driverLicenseInfo;

            }
        }else {
            return null;
        }

        return null;
    }

    /**
     * 模拟表单提交
     *
     * @param caseId 案件编号
     * @return 返回结果
     */
    private String emulatorLogin(final String caseId) {
        try {
            CloseableHttpClient httpClient = HttpClientUtil.getClient();
            HttpPost httpPost = new HttpPost("http://221.224.13.5:9090/GovAffairs/Wsbzcx/CertificateSchedule.aspx");
            HttpEntity httpEntity = new UrlEncodedFormEntity(new ArrayList<NameValuePair>() {{
                add(new BasicNameValuePair("ctl00$toolkitScriptManager", "ctl00$toolkitScriptManager|ctl00$contentPlaceHolder$ImageButton2"));
                add(new BasicNameValuePair("ctl00_toolkitScriptManager_HiddenField", ""));
                add(new BasicNameValuePair("ctl00$contentPlaceHolder$resultHF", ""));
                add(new BasicNameValuePair("ctl00$contentPlaceHolder$TextYWBH", caseId));
                add(new BasicNameValuePair("__LASTFOCUS", ""));
                add(new BasicNameValuePair("__EVENTTARGET", ""));
                add(new BasicNameValuePair("__EVENTARGUMENT", ""));
                add(new BasicNameValuePair("__VIEWSTATE", "/wEPDwUKMTkwMjQzNjQ4Ng9kFgJmD2QWAgIDD2QWAgIDD2QWBAIDDw8WAh4EVGV4dAUOMjEyMzIyMzIzMjIzMjNkZAIHD2QWAgIBD2QWAmYPZBYEAgEPFgIeC18hSXRlbUNvdW50Av////8PZAIFDw8WAh8AZWRkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYBBSVjdGwwMCRjb250ZW50UGxhY2VIb2xkZXIkSW1hZ2VCdXR0b24y"));
                add(new BasicNameValuePair("__EVENTVALIDATION", "/wEWBAKSsf7bAwKQgoq9CQK+7cqeBwKdmuipDA=="));
                add(new BasicNameValuePair("__ASYNCPOST", "true"));
                add(new BasicNameValuePair("ctl00$contentPlaceHolder$ImageButton2.x", "39"));
                add(new BasicNameValuePair("ctl00$contentPlaceHolder$ImageButton2.y", "10"));
            }});
            httpPost.setHeader("Accept", "*/*");
            httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch");
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setHeader("Cookie", "ASP.NET_SessionId=3bryalbeyyw2kwqnhhyr2uzi");
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36");
            httpPost.setHeader("Origin", "http://221.224.13.5:9090");
            httpPost.setHeader("Referer", "http://221.224.13.5:9090/GovAffairs/Wsbzcx/CertificateSchedule.aspx");
            httpPost.setHeader("X-MicrosoftAjax", "Delta=true");
            httpPost.setEntity(httpEntity);
            CloseableHttpResponse response;
            response = httpClient.execute(httpPost);
            try {
                return EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            } finally {
                response.close();
                httpPost.abort();
                httpPost.releaseConnection();
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public Result loadMonitorPicture(String localHostIP, String equipmentid) {
        String cacheKey = "MONITOR:IMG:" + equipmentid;
        if (super.exists(cacheKey))
            return new Result(Result.SUCC, super.get(cacheKey), "文件加载成功");
        Road road = roadMapper.findByEquipmentId(equipmentid);		   
        if (null == road || null == road.getRoadNameContent())        	
        	return new Result(Result.FAILURE, "暂无监控点数据");        	
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		   
		try {
			String roadTime = sd.format(road.getRoadImageTime());
			Date date1 = sd.parse(roadTime);
			String data = sd.format(new Date());
			Date date2 = sd.parse(data);
			long number1 = date2.getTime() - date1.getTime();
			long number2 = 3600000;
			long timeGap = number1 -number2;
			if (timeGap > 0) {// 超过一小时不显示图片
				return new Result(Result.FAILURE, "暂无监控点数据");
			} else {
				try {
					String _downloadUrl = transFile2Disk(localHostIP, road);
					if (null != _downloadUrl) {
						super.cache(cacheKey, _downloadUrl, 3 * 60);// 3分钟更新一次监控点图片
						return new Result(Result.SUCC, _downloadUrl, "图片加载成功");
					}
					return new Result(Result.FAILURE, "图片加载失败");
				} catch (FileNotFoundException e) {
					e.printStackTrace();
					return new Result(Result.FAILURE, "图片加载失败");
				}
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
			return new Result(Result.FAILURE, "时间解析异常");
		}
       
    }

    private String transFile2Disk(String localHostIP, Road road) throws FileNotFoundException {
        //Http服务器与文件服务器同机部署
//        if (Constant.SERVER_LOCALHOST_IP.equals(localHostIP) || localHostIP.equals(super.configInfo.getFileServerHost())) {
        //检测目录是否存在
        File _targetDir = FileUtils.makeDir(configInfo.getUploadSubDir("road"));
        if (null != _targetDir) {
            //图片压缩后存储于指定目录
            File _targetFile = new File(String.format("%s/%s.jpg", _targetDir.getPath(), road.getEquipmentId()));
            ImageUtil.resize(new ByteArrayInputStream(road.getRoadNameContent()), new FileOutputStream(_targetFile), 800, "jpg");
            return configInfo.getFileDownloadUrl(String.format("/road/%s", _targetFile.getName()));
        } else {
            logger.error("创建目录失败，请检查是否有读写权限");
            return null;
        }
//        } else {//采用NFS网络文件系统进行文件存储
//            //FIXME:下一阶段进行Linxu下 NFS配置
//            return null;
//        }
    }

    @Override
    public Result loadRoadImages(String localHostIP, int pageSize, int pageIndex) {
        PageHelper.startPage(pageIndex, pageSize, false);
        List<Road> roads = roadMapper.findRoadListByPage(new Query(pageSize, pageIndex));
        JSONArray array = new JSONArray();
        for (Road road : roads) {
            JSONObject object = new JSONObject();
            object.put("path", getRoadImagePath(localHostIP, road.getEquipmentId()).getData());
            object.put("equipmentId", road.getEquipmentId());
            object.put("equipmentName", road.getEquipmentName());
            array.add(object);
        }
        return new Result(array);
    }

    private Result getRoadImagePath(String localHostIP, String equipmentid) {
        String cacheKey = "MONITOR:IMG:" + equipmentid;
        if (super.exists(cacheKey))
            return new Result(Result.SUCC, super.get(cacheKey), "文件加载成功");
        Road road = roadMapper.findByEquipmentId(equipmentid);
        if (null == road)
            return new Result(Result.FAILURE, "无此监控点数据");
        if (null == road.getRoadNameContent())
            return new Result(Result.FAILURE, "无监控点照片");
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");		   
		try {
			String roadTime = sd.format(road.getRoadImageTime());
			Date date1 = sd.parse(roadTime);
			String data = sd.format(new Date());
			Date date2 = sd.parse(data);
			long number1 = date2.getTime() - date1.getTime();
			long number2 = 3600000;
			long timeGap = number1 - number2;
			if (timeGap > 0) {// 超过一小时不显示图片
				return new Result(Result.FAILURE, "暂无监控点数据");
			} else {
				try {
		            String path = transFile2Disk(localHostIP, road);
		            super.cache(cacheKey, path, 3 * 60);
		            return new Result(Result.SUCC, (Object) path);
		        } catch (Exception e) {
		            e.printStackTrace();
		            return new Result(Result.FAILURE, "监控点图片保存异常");
		        }
			}
		} catch (ParseException e1) {
			e1.printStackTrace();
			return new Result(Result.FAILURE, "时间解析异常");
		}
        
    }

    @Override
    public Result loadMonitorsByAddress(String address) {
        /*String cacheKey = "MONITOR:" + address;
        if (super.exists(cacheKey)) {
            return new Result(Result.SUCC, super.get(cacheKey));
        }*/
        List<Monitor> list = roadMapper.findMonitorByAddress(address);
        if (list.size() > 0) {
//            super.cache(cacheKey, list, 1f);//缓存一天
            return new Result(Result.SUCC, list);
        } else
            return new Result(Result.FAILURE, "暂无数据");
    }
    
    @Override
    public Result loadPassportImg(String localHostIP, String projectguid) {
//        String cacheKey = "PASSPORT_IMG:" + projectguid;
//        if (super.exists(cacheKey))
//            return new Result(Result.SUCC, super.get(cacheKey), "文件加载成功");
//        String url = super.configInfo.getGAApiUrl("ReportPage/PrintTXZInfo.aspx", "ProjectGuid", projectguid);
//        CloseableHttpResponse response = HttpClientUtil.getHttpResponse(url, null);
//        String photoName = projectguid + ".jpg";
//        String downloadPath = super.configInfo.getFileDownloadUrl((Constant.genPassportPath() + "/" + photoName));
//        try {
//            Result result = imagesHandle(localHostIP, Constant.genPassportPath(), downloadPath, photoName, response.getEntity().getContent());
//            if (result.isSucc())
//                super.cache(cacheKey, String.valueOf(result.getData()), 3 * 60);
//            return result;
//        } catch (Exception e) {
//            return new Result(Result.FAILURE, "图片保存出错");
//        }
        
        try {
        	String url = super.configInfo.getGAApiUrl("ReportPage/PrintTXZInfo.aspx", "ProjectGuid", projectguid);
            URL u = new URL(url);
            String photoName = projectguid + ".jpg";
            String targetDir = configInfo.getFileUploadRootPath() + "/" + Constant.genPassportPath()+"/"+photoName;
            String downloadPath = super.configInfo.getFileDownloadUrl((Constant.genPassportPath() + "/" + photoName));
            if(new File(targetDir).exists()){
            	System.out.println("========================文件已经存在");
            	return new Result(Result.SUCC, downloadPath, "");
            }
            OutputStream os = new FileOutputStream(targetDir);
    		Image img = Toolkit.getDefaultToolkit().getImage(u);
    		BufferedImage bi = com.oceansoft.mobile.econsole.modules.api.util.ImageUtil.toBufferedImage(img);
    		ImageIO.write(bi, "jpg", os);
    		os.close();
        	return new Result(Result.SUCC, downloadPath, "");
        } catch (Exception e) {
        	return new Result(Result.FAILURE, "图片保存出错");
        }
    }

    @Override
    public Result loadQRImg(String localHostIP, String projectguid) {
//        String cacheKey = "QR:" + projectguid;
//        if (super.exists(cacheKey))
//            return new Result(Result.SUCC, super.get(cacheKey), "文件加载成功");
//        String url = super.configInfo.getGAApiUrl("ReportPage/Txzbarcode.aspx", "ProjectGuid", projectguid);
//        CloseableHttpResponse response = HttpClientUtil.getHttpResponse(url, null);
//        String photoName = projectguid + "_qr.jpg";
//        String downloadPath = super.configInfo.getFileDownloadUrl((Constant.genPassportPath() + "/" + photoName));
//        try {
//            Result result = imagesHandle(localHostIP, Constant.genPassportPath(), downloadPath, photoName, response.getEntity().getContent());
//            if (result.isSucc())
//                super.cache(cacheKey, String.valueOf(result.getData()), 3 * 60);
//            return result;
//        } catch (Exception e) {
//            return new Result(Result.FAILURE, "图片保存出错");
//        } 
    	try {
    		String url = super.configInfo.getGAApiUrl("ReportPage/Txzbarcode.aspx", "ProjectGuid", projectguid);
            URL u = new URL(url);
            String photoName = projectguid + "_qr.jpg";
            String targetDir = configInfo.getFileUploadRootPath() + "/" + Constant.genPassportPath()+"/"+photoName;
            String downloadPath = super.configInfo.getFileDownloadUrl((Constant.genPassportPath() + "/" + photoName));
            if(new File(targetDir).exists()){
            	System.out.println("========================文件已经存在");
            	return new Result(Result.SUCC, downloadPath, "");
            }
            OutputStream os = new FileOutputStream(targetDir);
    		Image img = Toolkit.getDefaultToolkit().getImage(u);
    		BufferedImage bi = com.oceansoft.mobile.econsole.modules.api.util.ImageUtil.toBufferedImage(img);
    		ImageIO.write(bi, "jpg", os);
    		os.close();
        	return new Result(Result.SUCC, downloadPath, "");
        } catch (Exception e) {
        	return new Result(Result.FAILURE, "图片保存出错");
        }
    }

    /**
     * //如果当前部署节点与文件服务器在同一机器上则直接存储本地文件,否则需要通过smb将图片上传至文件服务器
     *
     * @param localHostIP 本地IP
     * @param uploadPath  上传路径
     * @param fileName    文件名称
     * @param inputStream 输入流
     * @throws Exception 图片处理异常
     */
    private Result imagesHandle(String localHostIP, String uploadPath, String downloadPath, String fileName, InputStream inputStream) {
        try {
//            if (Constant.SERVER_LOCALHOST_IP.equals(localHostIP) || localHostIP.equals(super.configInfo.getFileServerHost())) {
            String targetDir = configInfo.getFileUploadRootPath() + "/" + uploadPath;
            File targetFile = FileUtils.createFile(FileUtils.makeDir(targetDir), fileName);
            //byte[] bytes = new byte[inputStream.available()];
            //inputStream.read(bytes);
            ImageUtil.resize(inputStream, new FileOutputStream(targetFile), 800, "jpg");
            return new Result(Result.SUCC, downloadPath, "");
//            } else {
//                return null;
//            }
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("创建目录失败，请检查是否有读写权限");
            return null;
        } finally{
        	try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }

        /*
        InputStream ins = null;
        OutputStream out = null;
        try {
            String tempDir = configInfo.getFileUploadRootPath() + "/" + uploadPath + "/temp";
            String targetDir = configInfo.getFileUploadRootPath() + "/" + uploadPath;
            //本地存一份原图的临时文件
            File tempFile = FileUtils.createFile(FileUtils.makeDir(tempDir), fileName);
            FileUtils.createFile(inputStream, tempFile);
            //压缩后的图片文件
            File targetFile = FileUtils.createFile(FileUtils.makeDir(targetDir), fileName);
            //压缩
            ins = new FileInputStream(tempFile);
            out = new FileOutputStream(targetFile);
            ImageUtil.resize(ins, out, 800, "jpg");

            //删除临时目录
            logger.debug("LocalHostIP=" + localHostIP + ",FileServerHost=" + super.configInfo.getFileServerHost());
            org.apache.commons.io.FileUtils.forceDelete(new File(tempDir));
            if (localHostIP.equals(super.configInfo.getFileServerHost())) {
                return new Result(Result.SUCC, downloadPath, "文件加载成功");
            } else {
                String remotePath = FileUtils.smbPut(super.configInfo.getSmbFolder() + "/" + uploadPath, new FileInputStream(targetFile), fileName);
                if (null != remotePath) {
                    //存储至远程文件服务器  删除本地保存的文件
                    //org.apache.commons.io.FileUtils.forceDelete(new File(targetDir));
                    return new Result(Result.SUCC, downloadPath, "文件加载成功");
                }
                return new Result(Result.FAILURE, "图片读取失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(Result.FAILURE, "图片保存失败");
        } finally {
            try {
                if (ins != null) {
                    ins.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        */
    }

    @Override
    public Result loadMonitorsInfo() {
        /*String cacheKey = "MONITORS:LIST:ALL";
        if (super.exists(cacheKey)) {
            return new Result(Result.SUCC, super.getObject(cacheKey), "加载成功");
        } else {
            List<Monitor> rt = roadMapper.loadMonitors();
            if (!CollectionUtils.isEmpty(rt)) {
                for (Monitor r : rt) {
                    r.setLineId("");
                }
            }
            if (null != rt && rt.size() > 0) {
                super.cache(cacheKey, rt, 300);//缓存5分钟
                return new Result(Result.SUCC, rt);
            }
            return new Result(Result.FAILURE, "暂无数据");
        }*/
        List<Monitor> rt = roadMapper.loadMonitors();
        if (!CollectionUtils.isEmpty(rt)) {
            for (Monitor r : rt) {
                r.setLineId("");
                if(org.apache.commons.lang.StringUtils.isBlank(r.getLat())
                        || org.apache.commons.lang.StringUtils.isBlank(r.getLng())){
                    r.setLat("");
                    r.setLng("");
                }
            }
        }
        if (null != rt && rt.size() > 0) {
            return new Result(Result.SUCC, rt);
        }
        return new Result(Result.FAILURE, "暂无数据");
    }

    public ApiMessage getApiMessage(String pushType,String pushId){
        ApiMessage message = null;
        if(pushType.equals(PushChannel.APP.toString())){
            message = new AppMessage();
            ((AppMessage)message).setReceiver(pushId);

        }else if(pushType.equals(PushChannel.SMS.toString())){
            message = new SMSMessage();
            ((SMSMessage)message).setReceiver(pushId);

        }else if(pushType.equals(PushChannel.WECHAT.toString())){
            String pushTemplateId = WechatMessage.WECHAT_TEMPLATEID;
            message = new WechatMessage();
            ((WechatMessage)message).setOpenId(pushId);
            ((WechatMessage)message).setTempId(pushTemplateId);
        }
        return message;
    }

    @Override
    public Result queryResultGain(String action, String command) {

        OutQueryServiceInfo outQueryServiceInfo = jlApiService.queryOutServiceInfoByCondition(action,command);
        if(action.equals(InQueryServiceInfo.API_002) && null != outQueryServiceInfo){
            if(StringUtils.isNotBlank(outQueryServiceInfo.getRes())){
                // 获取机动车违法列表成功、状态码为 100101
                List<OffenseVehicleInfo> list = JSONArray.parseArray(outQueryServiceInfo.getRes(),OffenseVehicleInfo.class);
                return new Result(Result.SUCC,Constant.STATUS_CODE_100101,list,"获取机动车违法列表成功");
            }else{
                if(outQueryServiceInfo.getCode()=="111111"){
                    return new Result(Result.FAILURE,Constant.STATUS_CODE_100199,null,"您输入的发动机号与车牌号不匹配，请确认后再查询！");
                }
            }

        }

        if(action.equals(InQueryServiceInfo.API_006) && null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())){
            // 获取重名查询结果成功、状态码为 100101
            NameSakeInfo nameSakeInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), NameSakeInfo.class);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100101,nameSakeInfo,"获取重名查询结果成功");
        }

        if(action.equals(InQueryServiceInfo.API_007) && null != outQueryServiceInfo && StringUtils.isNotBlank(outQueryServiceInfo.getRes())){
            // 获取驾驶证记分成功、状态码为 100101
            DriverLicenseInfo driverLicenseInfo = JSONObject.parseObject(outQueryServiceInfo.getRes(), DriverLicenseInfo.class);
            return new Result(Result.SUCC,Constant.STATUS_CODE_100101,driverLicenseInfo,"获取驾驶证记分成功");
        }

        if(InQueryServiceInfo.API_002.equals(action)){
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100198,null,"目前无违章记录！");
        }else{
            return new Result(Result.FAILURE,Constant.STATUS_CODE_100198,null,"没有查询到相应的数据");
        }

    }
    @Override
    @Transactional
    public Result loadPolice(HttpServletRequest request) {
        String method = request.getParameter("methodType");
        String content = request.getParameter("content");
        if (Strings.isNullOrEmpty(method) || Strings.isNullOrEmpty(content)) {
            return new Result(Result.FAILURE, "查询失败，请重试!");
        }
        List<PoliceAddress> policeAddresses = Lists.newArrayList();
        if(method.equals("ORGNAME")){
            policeAddresses = mattersMapper.loadPoliceB(content);
        }else{
            policeAddresses = mattersMapper.loadPolice(method, content);
        }
        if(policeAddresses.size()!=0) {
            return new Result(Result.SUCC, policeAddresses);
        }else{
            return new Result(Result.FAILURE, "无符合项!");
        }
    }

    @Override
    @Transactional
    public Result loadPolicexq(String id) {
        List<PoliceAddress> list = mattersMapper.loadPolicexq(id);
        if(null != list && 0 < list.size()){
            return new Result(Result.SUCC,list.get(0));
        }
        return new Result(Result.FAILURE);
    }

    @Override
    @Transactional
    public Result sendMessage(String telNum, String content) {
        //System.out.print(content);
        SMSMessage smsMessage = new SMSMessage();
        smsMessage.setReceiver(telNum);
        smsMessage.setContent(content);
        String resp = HttpClientUtil.doPostString(configInfo.getSmsSendUrl(),smsMessage);
        if (StringUtils.isNotBlank(resp)) {
            JSONObject data = JSON.parseObject(resp);
            boolean succ = "true".equalsIgnoreCase(data.getString("succ"));
            //是否请求成功
            if (succ) {
                return new Result(Result.SUCC, "信息发送成功");
            } else {
                return new Result(Result.FAILURE, data.getString("msg"), "信息发送失败");
            }
        }
        return new Result(Result.FAILURE, "信息发送失败");
    }
}